package com.cy.Controller;

import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class ConsumerController{
//    @Bean
//    public IRule iRule(){//指定负载均衡的算法
//        return new RandomRule();//默认的轮训
//        return new NULL;//可以自己写负载均衡的方法
//    }
    @Bean//写在配置类@Configeration注解描述的类里
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
    @Bean
    @LoadBalanced
    public RestTemplate loadBalancedRestTemplate(){
        return new RestTemplate();
    }
    @Value("${spring.application.name}")
    private String appName;
    @Autowired
    private LoadBalancerClient loadBalancerClient;
//    @Autowired
//    private RestTemplate loadBalancedRestTemplate;
    @Autowired
    private RestTemplate restTemplate;
//    @GetMapping("/consumer/doLoadBalanced")
//    public String doRestLoadBalancedEcho(){
//        //假如RestTemplate对象由LoadBalanced注解描述，在编写url时，应该用服务名替换ip和port
//        String url=String.format("http://%s/provider/echo/%s","nacos-provider",appName);
//        return loadBalancedRestTemplate.getForObject(url, String.class);
//    }
    @GetMapping("/consumer/doRestEcho")
    public String doRestEcho(){
        ServiceInstance serviceInstance =
                loadBalancerClient.choose("nacos-provider");
        String url = String.format("http://%s:%s/provider/echo/%s",
                serviceInstance.getHost(),
                serviceInstance.getPort(),
                appName);
        System.out.println("request url:"+url);
        return restTemplate.getForObject(url, String.class);
    }
}
